GitLab CI/CD: Single job for multiple conditions

At a previous post, I used following configuration to achive manual or scheduled job at GitLab CI/CD.

.docker_build_base: &docker_build
  image: docker:latest
  stage: build_image
  services:
    - docker:dind
  script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
    - docker pull $CI_REGISTRY_IMAGE/build:latest || true
    - docker build --pull=true --cache-from $CI_REGISTRY_IMAGE/build:latest -t $CI_REGISTRY_IMAGE/build:latest .
    - docker run $CI_REGISTRY_IMAGE/build:latest
    - docker push $CI_REGISTRY_IMAGE/build:latest

docker_build_schedule:
  <<: *docker_build
  only:
    - schedules

docker_build_manual:
  <<: *docker_build
  when: manual
  except:
    - schedules

After that, rules was introduced and we can finally achieve multiple conditions with a single job! ( Ref)

Moreover, we can switch configurations depending on the condition. Here is an example. For schedule job, this job runs always. For non scheduled job, this job is kicked only manually, and failure is allowed (= can be skipped).

docker_build:
  image: docker:latest
  stage: build_image
  services:
    - docker:dind
  script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
    - docker pull $CI_REGISTRY_IMAGE/build:latest || true
    - docker build --pull=true --cache-from $CI_REGISTRY_IMAGE/build:latest -t $CI_REGISTRY_IMAGE/build:latest .
    - docker push $CI_REGISTRY_IMAGE/build:latest
  rules:
    - if: '$CI_PIPELINE_SOURCE == "schedule"'
      when: always
    - if: '$CI_PIPELINE_SOURCE != "schedule"'
      when: manual
      allow_failure: true
Avatar
Hiroyuki Yamada

My research interests include machine learning, cloud native conputing.

Related